package com.offcn.sellergoods.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.offcn.entity.PageResult;
import com.offcn.sellergoods.dao.*;
import com.offcn.sellergoods.entity.GoodsEntity;
import com.offcn.sellergoods.pojo.Goods;
import com.offcn.sellergoods.pojo.GoodsDesc;
import com.offcn.sellergoods.pojo.Item;
import com.offcn.sellergoods.pojo.ItemCat;
import com.offcn.sellergoods.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Timer;

/****
 * @Author:ujiuye
 * @Description:Goods业务层接口实现类
 * @Date 2021/2/1 14:19
 *****/
@Service
@Transactional
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {


    /**
     * Goods条件+分页查询
     * @param goods 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public PageResult<Goods> findPage(Goods goods, int page, int size){
         Page<Goods> mypage = new Page<>(page, size);
        QueryWrapper<Goods> queryWrapper = this.createQueryWrapper(goods);
        IPage<Goods> iPage = this.page(mypage, queryWrapper);
        return new PageResult<Goods>(iPage.getTotal(),iPage.getRecords());
    }

    /**
     * Goods分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageResult<Goods> findPage(int page, int size){
        Page<Goods> mypage = new Page<>(page, size);
        IPage<Goods> iPage = this.page(mypage, new QueryWrapper<Goods>());

        return new PageResult<Goods>(iPage.getTotal(),iPage.getRecords());
    }

    /**
     * Goods条件查询
     * @param goods
     * @return
     */
    @Override
    public List<Goods> findList(Goods goods){
        //构建查询条件
        QueryWrapper<Goods> queryWrapper = this.createQueryWrapper(goods);
        //根据构建的条件查询数据
        return this.list(queryWrapper);
    }


    /**
     * Goods构建查询对象
     * @param goods
     * @return
     */
    public QueryWrapper<Goods> createQueryWrapper(Goods goods){
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if(goods!=null){
            // 主键
            if(!StringUtils.isEmpty(goods.getId())){
                 queryWrapper.eq("id",goods.getId());
            }
            // 商家ID
            if(!StringUtils.isEmpty(goods.getSellerId())){
                 queryWrapper.eq("seller_id",goods.getSellerId());
            }
            // SPU名
            if(!StringUtils.isEmpty(goods.getGoodsName())){
                 queryWrapper.eq("goods_name",goods.getGoodsName());
            }
            // 默认SKU
            if(!StringUtils.isEmpty(goods.getDefaultItemId())){
                 queryWrapper.eq("default_item_id",goods.getDefaultItemId());
            }
            // 状态
            if(!StringUtils.isEmpty(goods.getAuditStatus())){
                 queryWrapper.eq("audit_status",goods.getAuditStatus());
            }
            // 是否上架
            if(!StringUtils.isEmpty(goods.getIsMarketable())){
                 queryWrapper.eq("is_marketable",goods.getIsMarketable());
            }
            // 品牌
            if(!StringUtils.isEmpty(goods.getBrandId())){
                 queryWrapper.eq("brand_id",goods.getBrandId());
            }
            // 副标题
            if(!StringUtils.isEmpty(goods.getCaption())){
                 queryWrapper.eq("caption",goods.getCaption());
            }
            // 一级类目
            if(!StringUtils.isEmpty(goods.getCategory1Id())){
                 queryWrapper.eq("category1_id",goods.getCategory1Id());
            }
            // 二级类目
            if(!StringUtils.isEmpty(goods.getCategory2Id())){
                 queryWrapper.eq("category2_id",goods.getCategory2Id());
            }
            // 三级类目
            if(!StringUtils.isEmpty(goods.getCategory3Id())){
                 queryWrapper.eq("category3_id",goods.getCategory3Id());
            }
            // 小图
            if(!StringUtils.isEmpty(goods.getSmallPic())){
                 queryWrapper.eq("small_pic",goods.getSmallPic());
            }
            // 商城价
            if(!StringUtils.isEmpty(goods.getPrice())){
                 queryWrapper.eq("price",goods.getPrice());
            }
            // 分类模板ID
            if(!StringUtils.isEmpty(goods.getTypeTemplateId())){
                 queryWrapper.eq("type_template_id",goods.getTypeTemplateId());
            }
            // 是否启用规格
            if(!StringUtils.isEmpty(goods.getIsEnableSpec())){
                 queryWrapper.eq("is_enable_spec",goods.getIsEnableSpec());
            }
            // 是否删除
            if(!StringUtils.isEmpty(goods.getIsDelete())){
                 queryWrapper.eq("is_delete",goods.getIsDelete());
            }
        }
        return queryWrapper;
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(Long id){
        Goods goods = goodsMapper.selectById(id);
        goods.setIsDelete("1");
        goods.setAuditStatus("0");
        goodsMapper.updateById(goods);
    }

    /**
     * 修改Goods
     * @param goodsEntity
     */
    @Override
    public void update(GoodsEntity goodsEntity){
        // 商品状态变为未审核
        goodsEntity.getGoods().setAuditStatus("0");
        goodsMapper.updateById(goodsEntity.getGoods());
        goodsDescMapper.updateById(goodsEntity.getGoodsDesc());
        QueryWrapper<Item> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id",goodsEntity.getGoods().getId());
        itemMapper.delete(wrapper);
        // 重新添加item
        this.saveItem(goodsEntity);
    }
    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsDescMapper goodsDescMapper;

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private ItemCatMapper itemCatMapper;

    @Autowired
    private BrandMapper brandMapper;
    /**
     * 增加Goods
     * @param goodsEntity
     */
    @Override
    public void add(GoodsEntity  goodsEntity){
        // 设置商品状态为未审核
        goodsEntity.getGoods().setAuditStatus("0");
        // 先保存goods表
        goodsMapper.insert(goodsEntity.getGoods());
        // 保存商品的扩展信息  先设置goodsId
        goodsEntity.getGoodsDesc().setGoodsId(goodsEntity.getGoods().getId());
        goodsDescMapper.insert(goodsEntity.getGoodsDesc());
        //  保存item   sku
        this.saveItem(goodsEntity);
    }
    private void setItemValue(GoodsEntity goodsEntity, Item item){
        // 商品分类
        item.setCategoryId(goodsEntity.getGoods().getCategory3Id());
        // 创建时间
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        // SPUid
        item.setGoodsId(goodsEntity.getGoods().getId());
        // 商家id
        item.setSellerId(goodsEntity.getGoods().getSellerId());
        // 分类名称
        ItemCat itemCat = itemCatMapper.selectById(goodsEntity.getGoods().getCategory3Id());
        item.setCategory(itemCat.getName());
        // 品牌名称
        item.setBrand(brandMapper.selectById(goodsEntity.getGoods().getBrandId()).getName());
        // 商品图片
        List<Map> imageList = JSON.parseArray(goodsEntity.getGoodsDesc().getItemImages(),Map.class);
        if (imageList.size() > 0 ){
            item.setImage((String) imageList.get(0).get("url"));
        }
    }
    private void saveItem(GoodsEntity goodsEntity){
        if ("1".equals(goodsEntity.getGoods().getIsEnableSpec())){
            // 保存sku
            if (!CollectionUtils.isEmpty(goodsEntity.getItemList())){
                for (Item item : goodsEntity.getItemList()) {
                    // 设置title  sku名称= goodsName +
                    String title = goodsEntity.getGoods().getGoodsName();
                    // { 网络：移动5G ， 机身内存： 128G}
                    Map<String ,String > map = JSON.parseObject(item.getSpec(), Map.class);
                    for (String key : map.keySet()) {
                        title += map.get(key) + " ";
                    }
                    // sku名称
                    item.setTitle(title);
                    item.setStatus("2");
                    this.setItemValue(goodsEntity,item);
                    itemMapper.insert(item);
                }
            }
        } else {
            // 选择不启用规格，sku的信息为默认值
            Item item = new Item();
            item.setTitle(goodsEntity.getGoods().getGoodsName());
            item.setPrice(goodsEntity.getGoods().getPrice());
            item.setNum(99999);
            item.setStatus("2");
            item.setIsDefault("1");
            item.setSpec("{}");
            this.setItemValue(goodsEntity,item);
            itemMapper.insert(item);
        }
    }

    /**
     * 根据ID查询Goods
     * @param id
     * @return
     */
    @Override
    public GoodsEntity findById(Long id){
        Goods goods = goodsMapper.selectById(id);
        GoodsDesc goodsDesc = goodsDescMapper.selectById(id);
        QueryWrapper<Item> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id",id);
        List<Item> itemList = itemMapper.selectList(wrapper);
        GoodsEntity goodsEntity = new GoodsEntity();
        goodsEntity.setGoods(goods);
        goodsEntity.setGoodsDesc(goodsDesc);
        goodsEntity.setItemList(itemList);
        return goodsEntity;
    }

    /**
     * 查询Goods全部数据
     * @return
     */
    @Override
    public List<Goods> findAll() {
        return this.list(new QueryWrapper<Goods>());
    }

    @Override
    public void auditGoods(Long goodsId) {
        Goods goods = goodsMapper.selectById(goodsId);
        if (goods.getIsDelete().equals("1")){
            throw new RuntimeException("该商品已被删除");
        }
        goods.setAuditStatus("1");
        goods.setIsMarketable("1");
        goodsMapper.updateById(goods);
    }
    //TODO 批量审核    批量上架   批量下架

}
